const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    moveStartX: 0,
    moveEndX: 0,
    moveStatus: false,
    checkAllStatus: false,
    total: '0.00', //合计
    showFoot: true,
    delAttr:[]
  },
  moveStart(e) {
    this.setData({
      moveStartX: e.touches[0].pageX,
      moveStatus: false
    })
  },
  move(e) {
    this.setData({
      moveEndX: e.touches[0].pageX,
      moveStatus: true
    })
  },
  moveEnd(e) {
    let that = this;
    let moveStartX = that.data.moveStartX;
    let moveEndX = that.data.moveEndX;
    let id = e.target.dataset.id;
    let list = that.data.cartList;
    list.forEach(i => {
      if (i.id == id) {
        if (that.data.moveStatus) {
          if ((moveStartX - moveEndX) > 50) { //向左
            i.showRadio = false;
            i.showDel = true;
          } else if (moveStartX < moveEndX) { //向右
            i.showRadio = true;
            i.showDel = false;
          }
        } else {
          // console.log('没移动')
          wx.navigateTo({
            url: '../pur-detail/pur-detail?id=' + id,
          })
        }
        that.setData({
          moveStatus: false
        })
      }
    })
    that.setData({
      cartList: list
    })
  },
  del(e) {
    let that = this;
    let id = e.target.dataset.id;
    let list = that.data.cartList;
    wx.showModal({
      title: '提示',
      content: '确定要删除当前商品？',
      success(res) {
        if (res.confirm) {
          let ids = [];
          let delItem = list.filter(i => i.id == id)[0].cart;
          delItem.forEach(i => {
            ids.push(i.id)
          })
          // console.log(ids)
          wx.request({
            url: app.buildUrl('/shop/shopping-cart/del-shopping-cart'),
            header: app.buildHeader(),
            method: "POST",
            data: {
              ids: ids
            },
            success(res) {
              if (res.data.code == 200) {
                list = list.filter(i => i.id != id);
                that.setData({
                  cartList: list
                })
                that.computeTotal()
                that.computeGoods()
              }
              app.showToast(res.data.msg)
            }
          })
        }
      }
    })
  },
  add(e) { //加
    let that = this;
    let id = e.target.dataset.id;
    let attrId = e.target.dataset.attrid;
    let list = that.data.cartList;
    let item = list.filter(i => i.id == id)[0].cart.filter(i => i.id == attrId)[0];
    let num = item.goods_num
    let maxNum = item.goods_attr.inventory;
    num = ++num;
    if (num > maxNum) {
      app.showToast('不能大于剩余库存')
    } else {
      wx.request({
        url: app.buildUrl('/shop/shopping-cart/modify-shopping-cart'),
        header: app.buildHeader(),
        method: "POST",
        data: {
          id: attrId,
          goods_num: num
        },
        success(res) {
          if (res.data.code == 200) {
            list.forEach(i => {
              if (i.id == id) {
                i.cart.forEach(i => {
                  if (i.id == attrId) {
                    i.goods_num = num
                  }
                })
              }
            })
            that.setData({
              cartList: list
            })
            that.computeTotal()
            that.computeGoods()
          }
        }
      })
    }
  },
  minus(e) { //减
    let that = this;
    let id = e.target.dataset.id;
    let attrId = e.target.dataset.attrid;
    let list = that.data.cartList;
    let item = list.filter(i => i.id == id)[0].cart.filter(i => i.id == attrId)[0];
    let num = item.goods_num
    let maxNum = item.goods_attr.inventory;
    num = --num;
    if (num > maxNum) {
      list.forEach(i => {
        if (i.id == id) {
          i.cart.forEach(i => {
            if (i.id == attrId) {
              i.goods_num = num;
              i.maxStatus = true
            }
          })
        }
      })
      that.setData({
        cartList: list
      })
      return;
    } else {
      list.forEach(i => {
        if (i.id == id) {
          i.cart.forEach(i => {
            if (i.id == attrId) {
              i.goods_num = num;
              i.maxStatus = false
            }
          })
        }
      })
      that.setData({
        cartList: list
      })
    }
    if (num == 0) {
      wx.showModal({
        title: '提示',
        content: '数量为0将会移除当前所选属性',
        success(res) {
          if (res.confirm) {
            wx.request({
              url: app.buildUrl('/shop/shopping-cart/del-shopping-cart'),
              header: app.buildHeader(),
              method: "POST",
              data: {
                ids: [attrId]
              },
              success(res) {
                if (res.data.code == 200) {
                  list.forEach(i => {
                    if (i.id == id) {
                      if (i.cart.length == 1) {
                        list = list.filter(i => i.id != id);
                        that.setData({
                          cartList: list
                        })
                      } else {
                        list.forEach(i => {
                          if (i.id == id) {
                            i.cart = i.cart.filter(i => i.id != attrId)
                          }
                        })
                        that.setData({
                          cartList: list
                        })
                      }
                    }
                  })
                  that.computeTotal()
                  that.computeGoods()
                }
                app.showToast(res.data.msg)
              }
            })
          }else{
            list.forEach(i => {
              if (i.id == id) {
                i.cart.forEach(i => {
                  if (i.id == attrId) {
                    i.goods_num = 1;
                  }
                })
              }
            })
            that.setData({
              cartList: list
            })
          }
        }
      })
    } else {
      wx.request({
        url: app.buildUrl('/shop/shopping-cart/modify-shopping-cart'),
        header: app.buildHeader(),
        method: "POST",
        data: {
          id: attrId,
          goods_num: num
        },
        success(res) {
          if (res.data.code == 200) {
            list.forEach(i => {
              if (i.id == id) {
                i.cart.forEach(i => {
                  if (i.id == attrId) {
                    i.goods_num = num
                  }
                })
              }
            })
            that.setData({
              cartList: list
            })
            that.computeTotal()
            that.computeGoods()
          }
        }
      })

    }
  },
  checkGoods(e) { //商品勾选切换
    let that = this;
    let list = that.data.cartList;
    list.forEach(i => {
      if (i.id == e.target.dataset.id) {
        let inventoryLen = i.cart.filter(i => i.maxStatus == false).length; //记录有多少个属性库存可用
        if (inventoryLen == 0) {
          return;
        }
        if (i.checked) {
          i.checked = false;
          i.cart.forEach(i => {
            i.checked = false;
          })
          i.item_count = 0;
          i.item_price = '0.00';
        } else {
          let count = 0;
          let price = 0;
          i.checked = true;
          i.cart.forEach(i => {
            if (!i.maxStatus) {
              i.checked = true;
              count += parseInt(i.goods_num);
              price += i.goods_num * i.goods_attr.price;
            }
          })
          i.item_count = count;
          i.item_price = parseFloat(price).toFixed(2);
        }
      }
    })
    that.setData({
      cartList: list
    })
    that.judgeCheckAll()
    that.computeTotal();
    that.computeGoods()
  },
  attrCheck(e) { //商品属性勾选切换
    let that = this;
    let id = e.target.dataset.id;
    let attrId = e.target.dataset.attrid;
    let list = that.data.cartList;
    let status = true;
    let item = list.filter(i => i.id == id)[0].cart.filter(i => i.id == attrId)[0];
    if (item.maxStatus) {
      return;
    }
    list.forEach(i => {
      if (id == i.id) {
        i.cart.forEach(j => {
          if (attrId == j.id) {
            if (j.checked) {
              j.checked = false;
            } else {
              j.checked = true;
            }
          }
        })
      }
    })
    list.forEach(i => {
      if (id == i.id) {
        i.cart.forEach(j => {
          if (j.checked == false) {
            status = false;
          }
        })
      }
    })
    if (status) {
      list.forEach(i => {
        if (id == i.id) {
          i.checked = true
        }
      })
    } else {
      list.forEach(i => {
        if (id == i.id) {
          i.checked = false
        }
      })
    }
    that.setData({
      cartList: list
    })
    that.judgeCheckAll()
    that.computeTotal();
    that.computeGoods()
  },
  checkAll() { //全选
    let that = this;
    let list = that.data.cartList;
    if (that.data.checkAllStatus) {
      list.forEach(i => {
        i.checked = false;
        i.cart.forEach(i => {
          i.checked = false;
        })
      })
      that.setData({
        checkAllStatus: false
      })
    } else {
      list.forEach(i => {
        let inventoryLen = i.cart.filter(j => j.maxStatus == false).length;
        if (inventoryLen == 0) {
          return;
        }
        i.checked = true;
        i.cart.forEach(i => {
          if (!i.maxStatus) {
            i.checked = true;
          }
        })
      })
      that.setData({
        checkAllStatus: true
      })
    }
    that.setData({
      cartList: list
    })
    that.computeTotal()
    that.computeGoods()
  },
  judgeCheckAll() { //判断全选状态
    let that = this;
    let list = that.data.cartList;
    let status = true;
    list.forEach(i => {
      if (i.checked == false) {
        status = false;
      } else {
        i.cart.forEach(i => {
          if (i.checked == false) {
            status = false;
          }
        })
      }
    })
    that.setData({
      checkAllStatus: status
    })
  },
  computeGoods() { //计算单个商品件数和价格
    let that = this;
    let list = that.data.cartList;
    list.forEach(i => {
      if (i.status == 0 || i.is_del == 1) {
        return;
      }
      i.item_count = 0;
      i.item_price = 0;
      i.cart.forEach(j => {
        let count = 0;
        let price = 0;
        if (j.checked) {
          count += parseInt(j.goods_num);
          price += j.goods_num * j.goods_attr.price;
          i.item_count += count;
          i.item_price += price;
        }
      })
    })
    list.forEach(i => {
      i.item_price = parseFloat(i.item_price).toFixed(2)
    })
    that.setData({
      cartList: list
    })
  },
  computeTotal() { //计算总价
    let that = this;
    let list = that.data.cartList;
    let total = 0;
    list.forEach(i => {
      if (i.status == 0 || i.is_del == 1) {
        return;
      }
      i.cart.forEach(i => {
        if (i.checked) {
          total += Number(i.goods_num * i.goods_attr.price);
        }
      })
    })
    that.setData({
      total: parseFloat(total).toFixed(2)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      showFoot: options.type == 1 ? false : true
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this;
    wx.showLoading({
      title: '加载进货单',
    })
    wx.request({
      url: app.buildUrl('/shop/shopping-cart/get-lists'),
      header: app.buildHeader(),
      success(res) {
        wx.hideLoading()
        if (res.data.code == 200) {
          let list = res.data.data;
          let delAttr = [];
          //合并重复的属性
          list.forEach(i => {
            i.cart.sort((a, b) => { //排序goods_attr_id
              return parseInt(a.goods_attr_id) - parseInt(b.goods_attr_id)
            })
            for (let j = 0; j < i.cart.length; j++) {
              let attrId = i.cart[j].goods_attr_id;
              let goodsId = i.cart[j].goods_id;
              if (j != i.cart.length - 1) { //如果最后一个就return
                if (attrId == i.cart[j + 1].goods_attr_id && goodsId == i.cart[j + 1].goods_id) {
                  i.cart[j].goods_num = parseInt(i.cart[j].goods_num) + parseInt(i.cart[j + 1].goods_num);
                  i.cart[j].setStatus = true;
                  delAttr.push(i.cart[j + 1].id);
                  that.setData({
                    delAttr: delAttr
                  })
                  i.cart.splice(j + 1, 1)
                  j -= 1;
                }
              }
            }
          })
          // 修改最后保留的属性的数据
          list.forEach(i => {
            i.cart.forEach(i => {
              if (i.setStatus) {
                wx.request({
                  url: app.buildUrl('/shop/shopping-cart/modify-shopping-cart'),
                  header: app.buildHeader(),
                  method: "POST",
                  data: {
                    id: i.id,
                    goods_num: i.goods_num
                  },
                  success(res) {
                    if (res.data.code == 200) { }
                  }
                })
              }
            })
          })
          // 删除重复属性
          if (that.data.delAttr.length > 0){
            wx.request({
              url: app.buildUrl('/shop/shopping-cart/del-shopping-cart'),
              header: app.buildHeader(),
              method: "POST",
              data: {
                ids: that.data.delAttr
              },
              success(res) {
                if (res.data.code == 200) { }
              }
            })
          }
          list.forEach(i => {
            i.checked = false; //选择状态
            i.item_count = 0; //共多少件
            i.item_price = '0.00'; //小计
            i.showRadio = true;
            i.showDel = false;
            // 0精品商城   2推荐商品 3热门商品 4新品上线 5 限时折扣
            // console.log(i.goods_type)
            i.goods_type = i.goods_type == 0 ? "精品商城" : i.goods_type == 2 ? "推荐商品" : i.goods_type == 3 ? "热门商品" : i.goods_type == 4 ? "新品上线" : i.goods_type == 5 ? "限时折扣" : ""
            i.cart.forEach(j => {
              j.checked = false;
              j.goods_num = parseInt(j.goods_num);
              j.goods_attr.inventory = parseInt(j.goods_attr.inventory);
              j.maxStatus = j.goods_num > j.goods_attr.inventory;
              j.goods_attr.discount_price = parseFloat(j.goods_attr.discount_price).toFixed(2);
              j.goods_attr.original_price = parseFloat(j.goods_attr.original_price).toFixed(2);
              if (i.goods_type == '限时折扣') {
                j.goods_attr.price = parseFloat(j.goods_attr.discount_price).toFixed(2);
              } else {
                j.goods_attr.price = parseFloat(j.goods_attr.original_price).toFixed(2);
              }
            })
          })
          that.setData({
            cartList: list
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  }
})